<?php

namespace app\common\model;

use app\util\CurlRequest;
use think\Db;
use think\Model;
use think\Config;
use traits\model\SoftDelete;

class ChatRoom extends Model
{
    use SoftDelete;
    protected $resultSetType = 'collection';
    // 定义时间戳字段名
    protected $createTime = 'add_time';
    protected $deleteTime = 'delete_time';
    // 追加属性
    protected $append = ['user_info','info'];

    public static function chat_content_list($user_id)
    {
        $is_chao_kf = User::where("user_id",$user_id)->value("is_chao_kf");
//        $where = "(user_id = {$user_id} OR (group_type = 3 OR group_type = 4) AND to_id = {$user_id}) AND content != '0'";
        $where = "user_id = {$user_id} AND content != '0'";
        if($is_chao_kf == '0'){
            $where.= " AND is_kf = 0";
        }
        $field = "*";
        $order = "last_time DESC";
        $total = '';
        $list = self::where($where)->field($field)->order($order)->select();
        // echo Db::getLastSql();die();
        foreach ($list as &$value){
            if($value['type'] == 2){
                $value['content'] = '[图片]';
            }
            if($value['type'] == 3){
                $value['content'] = '[视频]';
            }
            $value['last_time'] = getChatTimeStr($value['last_time']);
            $value['room_ids'] = "";
            $value['content'] = str_replace(PHP_EOL,'', $value['content']);
//            if($user_id != $value["user_id"] && $value["information_id"] != '0' && ($value['group_type'] == 3 || $value['group_type'] == 4)){
//                $user_id = $value['user_id'];
//                $to_id = $value['to_id'];
//                $value['user_id'] = $to_id;
//                $value['to_id'] = $user_id;
//            }
        }
        $data = [
            'total'=>$total,
            'list'=>$list
        ];
        return $data;
    }
    public static function chat_content_info($user_id,$to_id,$group_type)
    {
        $where = "user_id = {$user_id}";
        $where.= " AND to_id = {$to_id}";
        $where.= " AND group_type = '{$group_type}'";
        $info = self::where($where)->field("*")->find();
        $info['room_ids'] = $info['group_room'];
        return $info;
    }
    
    public static function kf_content_info($group_room,$information_id,$group_type)
    {
        // $where = "user_id = {$user_id}";
        // $where.= " AND information_id = '{$information_id}";
        // $where.= " AND group_type = '{$group_type}'";
        $info = self::where("group_room",$group_room)->where(["information_id"=>$information_id,"group_type"=>$group_type])->field("*")->find();
        $info['room_ids'] = $info['group_room'];
        return $info;
    }

    public static function invite_info($chat_group_id,$invite_id)
    {
        $group_info = ChatGroup::where("id",$chat_group_id)->field("name,user_ids,price")->find();
        $invite_name = User::where("user_id",$invite_id)->value("username");
        $group_number = ChatRoom::where("to_id",$chat_group_id)->count();
        $images = User::where("user_id","IN",$group_info["user_ids"])->column("image");
        if($images){
            foreach ($images as &$value){
                $value = splicing_domain($value);
            }
        }else{
            $images = [];
        }
        $invite_info = [];
        $invite_info['username'] = $group_info["name"];
        $invite_info['image'] = $images;
        $invite_info['invite_name'] = $invite_name;
        $invite_info['invite_price'] = $group_info["price"];
        $invite_info['group_number'] = $group_number;
        return $invite_info;
    }

    public function getUserInfoAttr($value,$data)
    {
        Db::name("test")->where("id",1)->update(["workrange"=>$data['group_type']]);
        if($data['group_type'] == 1){
            $info = User::where("user_id",$data["to_id"])->field("username,image,authen,authen_time,deposit_price")->find();
            $user_info['username'] = $info["username"];
            $user_info['user_image'] = $info["image"];
            $user_info['users_number'] = [];
            $user_info['number'] = self::where(["user_id"=>$data['user_id'],"to_id"=>$data['to_id'],"group_type"=>$data['group_type'],"group_room"=>$data["group_room"]])->value("number");;
        }elseif ($data['group_type'] == 3){
            $info = User::where("user_id",$data["to_id"])->field("username,image,authen,authen_time,deposit_price")->find();
            $is_chao_kf = User::where("user_id",$data["user_id"])->value("is_chao_kf");
            if($is_chao_kf == '1'){
                $user_info['username'] = $info['username'];
            }else{
                $user_info['username'] = "平台客服";
            }
            $user_info['user_image'] = $info["image"];
            $user_info['users_number'] = [];
            $user_info['number'] = self::where(["user_id"=>$data['user_id'],"to_id"=>$data['to_id'],"group_type"=>$data['group_type'],"group_room"=>$data["group_room"]])->value("number");;
        }elseif ($data['group_type'] == 4){
            $information = Db::name("information")->where("id",$data["information_id"])->field("id,name,image")->find();
            $user_info['username'] = $information["name"];
            $user_info['user_image'] = splicing_domain($information["image"]);
            $user_info['users_number'] = [];
            $user_info['number'] = self::where(["user_id"=>$data['user_id'],"to_id"=>$data['to_id'],"group_type"=>$data['group_type'],"group_room"=>$data["group_room"]])->value("number");;
        }else{
            $group_info = Db::name("chat_group")->where("id",$data["to_id"])->field("id,name,user_ids")->find();
            if($group_info){
                $images = User::where("user_id","IN",$group_info["user_ids"])->limit(4)->column("image");
                if($images){
                    foreach ($images as &$value){
                        $value = splicing_domain($value);
                    }
                }else{
                    $images = [];
                }
                $user_info = [];
                $user_info['username'] = $group_info["name"];
                $user_info['user_image'] = $images;
                $user_info['number'] = self::where(["user_id"=>$data['user_id'],"to_id"=>$data['to_id'],"group_type"=>2,"group_room"=>$data["group_room"]])->value("number");
                $user_info['users_number'] = self::where(["to_id"=>$data['to_id']])->column("user_id,number");
            }else{
                $user_info = [];
                $user_info['username'] = '';
                $user_info['user_image'] = '';
                $user_info['number'] = '';
                $user_info['users_number'] = [];
            }
        }
        return $user_info;
    }

    public function getInfoAttr($value,$data)
    {
        if($data['group_type'] == 1){
            $info = User::where("user_id",$data["user_id"])->field("username,image,authen,authen_time,deposit_price")->find();
            $user_info['username'] = $info["username"];
            $user_info['user_image'] = $info["image"];
            $user_info['number'] = self::where(["user_id"=>$data['to_id'],"to_id"=>$data['user_id'],"group_type"=>$data['group_type'],"group_room"=>$data["group_room"]])->value("number");
            $user_info['users_number'] = [];
        }elseif ($data['group_type'] == 3){
            $info = User::where("user_id",$data["user_id"])->field("username,image,authen,authen_time,deposit_price")->find();
            $user_info['username'] = $info["username"];
            $user_info['user_image'] = $info["image"];
            $user_info['number'] = self::where(["user_id"=>$data['to_id'],"to_id"=>$data['user_id'],"group_type"=>$data['group_type'],"group_room"=>$data["group_room"]])->value("number");
            $user_info['users_number'] = [];
        }elseif ($data['group_type'] == 4){
            $information = Db::name("information")->where("id",$data["information_id"])->field("id,name,image")->find();
            $user_info['username'] = $information["name"];
            $user_info['user_image'] = splicing_domain($information["image"]);
            $user_info['number'] = self::where(["user_id"=>$data['to_id'],"to_id"=>$data['user_id'],"group_type"=>$data['group_type'],"group_room"=>$data["group_room"]])->value("number");
            $user_info['users_number'] = [];
        }else{
            $group_info = Db::name("chat_group")->where("id",$data["to_id"])->field("id,name,user_ids")->find();
            if($group_info){
                $images = User::where("user_id","IN",$group_info["user_ids"])->limit(4)->column("image");
                if($images){
                    foreach ($images as &$value){
                        $value = splicing_domain($value);
                    }
                }else{
                    $images = [];
                }
                $user_info = [];
                $user_info['username'] = $group_info["name"];
                $user_info['user_image'] = $images;
                $user_info['number'] = self::where(["user_id"=>$data['user_id'],"to_id"=>$data['to_id'],"group_type"=>2,"group_room"=>$data["group_room"]])->value("number");
                $user_info['users_number'] = [];
            }else{
                $user_info = [];
                $user_info['username'] = '';
                $user_info['user_image'] = '';
                $user_info['number'] = '';
                $user_info['users_number'] = [];
            }
        }
        return $user_info;
    }

    /**
     * @description: 获取 APP Token
     */
    public static function getAappToken()
    {
        $ring_config = Config::get("parameter.ring_config");
        $uri = "https://{$ring_config['rest_uri']}/{$ring_config['org_name']}/{$ring_config['app_name']}/token";
        $body = [
            'grant_type' => 'client_credentials', //授权方式。该参数设置为固定字符串 client_credentials，即客户端凭证模式
            'client_id' => $ring_config['client_id'], //App 的 client_id，用于生成 app token 调用 REST API
            'client_secret' => $ring_config['client_secret'], //App 的 client_secret，用于生成 app token 调用 REST API
            'ttl' => 0, //token 有效期单位为秒,,若设置为 0，则 token 永久有效,注意：VIP 5 集群该参数单位为毫秒
        ];
        $headers = [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers);
        file_put_contents("app_token.txt",json_encode($ret));
        return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
    }

    /**
     * @description: 获取 User Token
     */
    public static function getUserToken($username)
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];
        if (empty($username)) {
            return ['code' => 201, 'msg' => '用户名不能为空'];
        }
        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/token";
        $body = [
            'grant_type' => 'inherit', //若值为 inherit，通过用户 ID 获取 token，只需设置 username
            'username' => $username, //用户 ID
            'autoCreateUser' => true, //当用户不存在时，是否自动创建用户。自动创建用户时，需保证授权方式（grant_type）必须为 inherit
            'ttl' => 0, //token 有效期，单位为秒。设置为 0 则 token 有效期为永久,注意：VIP 5 集群该参数单位为毫秒
        ];
        $headers = [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'Authorization' => $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers);
        return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
    }

    // 发送单聊消息
    public static function sendToUser($from_username,$to_username,$msg)
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];

        $baseUrl = 'https://'.$config['rest_uri'].'/'.$config['org_name'].'/'.$config['app_name'].'/messages/users'; // 替换为你的实际URL

        // 消息内容
        $postData = [
            'from' => $from_username,
            'to' => [$to_username],
            'type' => 'txt',
            'body' => [
                'msg' => json_encode($msg)
            ],
            'ext' => [
                'em_ignore_notification' => false,
                // 自定义扩展字段，用于设置离线推送模板相关参数
                //'offline_push_ext' => [
                //    // 离线推送标题和内容
                //    'title' => $from_username,
                //    'content' => $msg['list']['content'],
                //    // 其他可选配置项...
                //],
            ],
             //'routetype' => 'ROUTE_ONLINE',
            'sync_device' => true
        ];

        $headers = [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'Authorization' =>  'Bearer ' . $appToken,
        ];
        $res = CurlRequest::sendCurlRequest($baseUrl,$postData,$headers);

        return $res;
    }

    // 发送群聊消息
    public static function sendToGroup($from_username,$group_id,$msg)
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];

        $baseUrl = 'https://'.$config['rest_uri'].'/'.$config['org_name'].'/'.$config['app_name'].'/messages/chatgroups'; // 替换为你的实际URL

        // 消息内容
        $postData = [
            'from' => $from_username,
            'to' => [$group_id],
            'type' => 'txt',
            'body' => [
                'msg' => json_encode($msg)
            ],
            'ext' => [
                'em_ignore_notification' => true
            ],
            'routetype' => 'ROUTE_ONLINE',
            'sync_device' => true
        ];

        $headers = [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'Authorization' =>  'Bearer ' . $appToken,
        ];
        $res = CurlRequest::sendCurlRequest($baseUrl,$postData,$headers);

        return $res;
    }

    /**
     * @description: 创建群组
     */
    public static function createGroup($group_name,$username)
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];
        if (empty($group_name)) {
            return ['code' => 201, 'msg' => '群组名不能为空'];
        }
        if (empty($username)) {
            return ['code' => 201, 'msg' => '群主用户名不能为空'];
        }
        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/chatgroups";
        $body = [
            'groupname' => $group_name, //群组名称，最大长度为 128 字符
            'public' => false, //是否是公开群。公开群可以被搜索到，用户可以申请加入公开群
            'allowinvites' => false, //是否允许普通群成员邀请用户加入群组
            'invite_need_confirm' => false, //邀请用户入群时是否需要被邀用户同意
            'owner' => $username,
        ];
        $headers = [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers);

        if (isset($ret['data']) && isset($ret['data']['groupid']) && !empty($ret['data']['groupid'])) {
            return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
        }else{
            return ['code' => 201, 'msg' => '请求失败', 'data' => $ret];
        }
    }

    /**
     * @description: 批量添加群组成员
     */
    public static function  groupAddUser($group_id,$usernames=[])
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];
        if (empty($group_id)) {
            return ['code' => 201, 'msg' => '群组ID不能为空'];
        }
        if (empty($usernames)) {
            return ['code' => 201, 'msg' => '群成员名称不能为空'];
        }
        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/chatgroups/{$group_id}/users";
        $body = [
            'usernames' => $usernames, //要添加为群组成员的用户 ID 数组，每次最多可传 60 个用户 ID
        ];
        $headers = [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers);

        if (isset($ret['data']) && isset($ret['data']['newmembers']) && !empty($ret['data']['newmembers'])) {
            return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
        }else{
            return ['code' => 201, 'msg' => '请求失败', 'data' => $ret];
        }
    }

    /**
     * @description: 获取APP下的所有群组
     */
    public static function getGroups($limit=1000,$cursor='')
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];

        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/chatgroups?limit={$limit}&cursor={$cursor}";
        $body = [];
        $headers = [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers, 'get');

        if (isset($ret['data']) && is_array($ret['data'])) {
            return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
        }else{
            return ['code' => 201, 'msg' => '请求失败', 'data' => $ret];
        }
    }

    /**
     * @description: 获取群组中的所有成员
     */
    public static function getGroupUsers($group_id,$pagenum=1,$pagesize=1000)
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];
        if (empty($group_id)) {
            return ['code' => 201, 'msg' => '群组ID不能为空'];
        }
        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/chatgroups/{$group_id}/users?pagenum={$pagenum}&pagesize={$pagesize}";
        $body = [];
        $headers = [
            'Authorization' => 'Bearer ' . $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers, 'get');

        if (isset($ret['data']) && !empty($ret['data'])) {
            return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
        }else{
            return ['code' => 201, 'msg' => '请求失败', 'data' => $ret];
        }
    }

    /**
     * @description: 批量移除群组成员
     */
    public static function groupDelUser($group_id,$usernames=[])
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];
        if (empty($group_id)) {
            return ['code' => 201, 'msg' => '群组ID不能为空'];
        }
        if (empty($usernames)) {
            return ['code' => 201, 'msg' => '群成员名称不能为空'];
        }

        $members = implode(',',$usernames);
        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/chatgroups/{$group_id}/users/{$members}";
        $body = [];
        $headers = [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers, 'delete');

        if (isset($ret['data']) && !empty($ret['data'])) {
            return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
        }else{
            return ['code' => 201, 'msg' => '请求失败', 'data' => $ret];
        }
    }

    /**
     * @description: 解散群组
     */
    public static function deleteGroup($group_id)
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];
        if (empty($group_id)) {
            return ['code' => 201, 'msg' => '群组ID不能为空'];
        }

        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/chatgroups/{$group_id}";
        $body = [];
        $headers = [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers, 'delete');

        if (isset($ret['data']) && isset($ret['data']['success']) && $ret['data']['success'] === true) {
            return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
        }else{
            return ['code' => 201, 'msg' => '请求失败', 'data' => $ret];
        }
    }

    /**
     * @description: 获取单个用户在线状态
     */
    public static function getUserStatus($username)
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];
        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/users/{$username}/status";
        $body = [];
        $headers = [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers, 'get');

        if (isset($ret['data']) && is_array($ret['data'])) {
            return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
        }else{
            return ['code' => 201, 'msg' => '请求失败', 'data' => $ret];
        }
    }

    /**
     * @description: 获取批量用户在线状态
     */
    public static function getBatchUserStatus($usernames = [])
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];
        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/users/batch/status";
        $body = [
            'usernames' => $usernames, //要查询状态的用户 ID，每次最多能传 100 个
        ];
        $headers = [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers, 'post');

        if (isset($ret['data']) && is_array($ret['data'])) {
            return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
        }else{
            return ['code' => 201, 'msg' => '请求失败', 'data' => $ret];
        }
    }

    /**
     * @description: 创建全量推送任务
     */
    public static function noticeMsg($msg)
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];
        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/push/task";
        $body = [
            'strategy' => 4, //只走环信通道且只推在线用户。离线用户收不到推送通知
            'pushMessage' => json_encode($msg),
        ];
        $headers = [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers, 'post');

        if (isset($ret['data']) && is_array($ret['data'])) {
            return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
        }else{
            return ['code' => 201, 'msg' => '请求失败', 'data' => $ret];
        }
    }

    /**
     * @description: 绑定和解绑推送信息
     */
    public static function binding($user_id,$device_id,$notifier_name,$device_token)
    {
        if(file_exists('app_token.txt')){
            $appTokenInfo = file_get_contents('app_token.txt');
            $appTokenInfo = json_decode($appTokenInfo,true);
        }else{
            $appTokenInfo = self::getAappToken();
        }
        $config = Config::get("parameter.ring_config");
        $appToken = $appTokenInfo["access_token"];
        if (empty($user_id)) {
            return ['code' => 201, 'msg' => '用户ID不能为空'];
        }
        if (empty($device_id)) {
            return ['code' => 201, 'msg' => '移动端设备标识不能为空'];
        }
        if (empty($notifier_name)) {
            return ['code' => 201, 'msg' => '推送证书名称不能为空'];
        }
        $uri = "https://{$config['rest_uri']}/{$config['org_name']}/{$config['app_name']}/users/{$user_id}/push/binding";
        $body = [
            'device_id' => $device_id,
            'notifier_name' => $notifier_name,
            'device_token' => $device_token,
        ];
        $headers = [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $appToken,
        ];
        $ret = CurlRequest::sendCurlRequest($uri, $body, $headers, 'put');
        if (isset($ret['data']) && isset($ret['data']['success']) && $ret['data']['success'] === true) {
            return ['code' => 200, 'msg' => '请求成功', 'data' => $ret];
        }else{
            return ['code' => 201, 'msg' => '请求失败', 'data' => $ret];
        }
    }

}
